<?php

declare(strict_types=1);

namespace app\shop\controller\api\order;

use think\Request;
use think\facade\Db;
use sheep\exception\SheepException;
use app\shop\controller\api\ShopBase;
use app\shop\model\order\Invoice as OrderInvoiceModel;

class Invoice extends ShopBase
{
    public function list(Request $request)
    {
        $user = $this->auth()->user();
        $params = $request->param();
        $type = $params['type'] ?? 'all';

        $invoices = OrderInvoiceModel::where('user_id', $user->id);

        switch ($type) {
            case 'cancel':
                $invoices = $invoices->cancel();
                break;
            case 'waiting':
                $invoices = $invoices->waiting();
                break;
            case 'finish':
                $invoices = $invoices->finish();
                break;
            default :
                $invoices = $invoices->show();  // 除了未支付的
                break;
        }

        $invoices = $invoices->order('id', 'desc')->paginate(request()->param('list_rows', 10));

        return success('获取成功', $invoices);
    }


    public function detail(Request $request, $id)
    {
        $user = $this->auth()->user();

        $invoice = OrderInvoiceModel::with(['order', 'order_items'])->where('user_id', $user->id)->findOrFail($id);
        $invoice->hidden([], false);     // 取消隐藏 order_items
        return success('获取成功', $invoice);
    }


    // 取消订单
    public function cancel(Request $request, $id)
    {
        $user = $this->auth()->user();

        $invoice = OrderInvoiceModel::where('user_id', $user->id)->waiting()->findOrFail($id);

        $invoice->status = 'cancel';
        $invoice->save();

        return success('取消成功', $invoice);
    }
}
